<template>
  <div class="record">
    <el-card class="box-card record-left myTree">
      <div class="record-left-header">
        <el-button
          size="middle"
          type="primary"
        >全部桥梁:800座</el-button>
        <!--<span><em class="el-icon-folder mRight6"></em>档案管理</span>-->
      </div>
      <div style="margin-top: -13px;display: flex" >
        <el-button type="primary">拱桥:100座</el-button>
        <el-button type="success">桥梁:100座</el-button>
      </div>
      <el-button type="info" style="margin-top: 4px">斜拉桥:100座</el-button>
      <div class="record-left-tree">
        <el-tree v-for="treeItem in $store.state.bridgeRecords.treeData" class="filter-tree" :key="treeItem.id"
                 :data="treeItem.data" :props="defaultProps" @node-click="handleNodeClick" ref="tree" node-key="id"
                 show-checkbox @check-change="handleCheckChange" :check-on-click-node="true" :check-strictly="true"
                 :default-checked-keys="checkedKeys" :default-expanded-keys="expandedKeys">
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span class="tree-text-length"> <i
              :class="((data['childFolders']&&data['childFolders'].length>0)||data.level===1)?'el-icon-folder':'el-icon-document'">
              </i>&nbsp;&nbsp;{{ data.label }}
            </span>
            <span>
              <el-button v-if="data.level===1" class="el-icon-edit" style="color: #bec4d0 !important;" type="text"
                         size="mini" @click="() => handleEditTree(node,data)"></el-button>
            </span>
          </span>
        </el-tree>

      </div>
    </el-card>
    <div class="record-right">
      <div class="record-searchBar">
        <div class="record-flexBetween">
          <div>
             <el-date-picker v-model="dateTime" value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss"
              type="datetimerange" start-placeholder="开始日期" end-placeholder="结束日期" range-separator="——" size="small"
              :default-time="['12:00:00']">
            </el-date-picker>
            <el-input placeholder="请输入关键字" v-model="searchName" size="small" class="mLeft20" style="width: 180px;">
            </el-input>
            <el-button size="small" type="primary" class="mLeft6 el-icon-search" @click="() => getListData(1)">
              查询
            </el-button>
          </div>
          <div>
            <el-button size="small" type="primary" icon="el-icon-plus" @click="handleAdd">
              新增档案
            </el-button>
          </div>
        </div>
      </div>
      <div class="record-content">
        <div class="record-content-header">
          <h4>设计文件</h4>
          <div class="record-content-header-btns">
            <el-button type="text" class="bold" icon="el-icon-download" @click="handleDownLoadList">
            </el-button>
            <el-button type="text" class="bold" icon="el-icon-edit-outline" @click="handleEditList">
            </el-button>
            <el-button type="text" icon="el-icon-delete" class="bold" style="color: red !important;"
                       @click="handleDeleteList">
            </el-button>
          </div>
        </div>
        <div class="record-content-main">
          <div class="record-content-list" v-if="listData.length>0">
            <div class="record-content-item" v-for="(item, index) in listData" :key="index">
              <div class="record-content-item-check" @click="() => handleCheck(index)">
                <i class="notCheck" v-if="!item.isCheck"></i>
                <i v-else class="el-icon-check hasCheck"></i>
              </div>
              <div class="record-content-item-bg">
                <span class="label">{{item.fileSuffix}}</span>
              </div>
              <div class="record-content-item-title">
                {{item.originalFileName}}
              </div>
            </div>
          </div>
          <div class="record-content-list" v-else>
            <div class="record-content-noData"></div>
          </div>
          <div class="record-content-page">
            <el-pagination background layout="prev, pager, next" :hide-on-single-page="true"
                           :current-page.sync="currentPage" @current-change="handlePageChange" :page-size="pageSize"
                           :total="recordsTotal">
            </el-pagination>
          </div>
        </div>
      </div>
    </div>
    <!--新增编辑档案弹框-->
    <vx-popup :title="recordPopupTitle" width="701px" @close="cancelFormSubmit" :active.sync="recordPopup"
              @confirmPopup="submit" @cancelPopup="cancelFormSubmit">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="桥梁名称 :">
          <el-select v-model="ownId" placeholder="请选择" size="small" style="width:100%" :disabled="true">
            <el-option v-for="item in bridgesList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文件夹名称 :">
          <el-input type="text" v-model="checkedIdName" size="small" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="上传文件 :" prop="recordFile">
          <el-upload class="upload-demo" :action="!editRecord?uploadUrl:updateUrl" :data="uploadParams"
                     :on-remove="handleRemove" :before-remove="beforeRemove" multiple :limit="editRecord?1:Infinity"
                     :on-exceed="handleExceed" :file-list="ruleForm.recordFile" :on-success="handleSuccess">
            <div class="record-upload el-icon-plus"></div>
          </el-upload>
          <span class="upload-labelInfo" v-show="editRecord">注: 编辑态，先删除原有文件，重新上传一个文件替换原有文件且只能上传一个文件</span>
        </el-form-item>
      </el-form>
    </vx-popup>
    <!--  -->
    <!--新增编辑档案树-->
    <vx-popup title="编辑档案" width="450px" @close="cancelTreeSubmit" :active.sync="treePopup"
              @confirmPopup="cancelTreeSubmit" @cancelPopup="cancelTreeSubmit">
      <TreeEdit :treeData="$store.state.bridgeRecords.editTreeData" ref="treeEdit" @query="getTreeData"></TreeEdit>
    </vx-popup>
  </div>
</template>
<script>
  import {
    mapState,
    mapGetters
  } from "vuex";
  import moment from "moment";
  import base from "@/api/base";
  import {
    deepClone
  } from "@/util.js";
  import TreeEdit from "./components/archivesEditTree";
  import {
    openDb,
    updateBridModel
  } from '@/indexDb';
  export default {
    data() {
      var validateRecordFiles = (rule, value, callback) => {
        if (this.ruleForm.recordFile.length <= 0) {
          callback(new Error('请上传文件'));
        } else {
          callback();
        }
      };
      return {
        uploadUrl: base.UPLOADURL,
        updateUrl: base.UPDATEFILE,
        uploadParams: {},
        defaultProps: {
          children: "childFolders",
          label: "label"
        },
        dateTime: [],
        startTime: '',
        endTime: '',
        checkedKeys: [],
        expandedKeys: [],
        checkedId: null,
        checkedIdName: '',
        ownId: null,
        bridgesList: [], //所有桥梁
        pageSize: 24,
        currentPage: 0,
        recordsTotal: 0,

        listData: [],
        searchName: "",
        recordPopup: false,
        recordPopupTitle: "新增档案",
        editRecord: false,
        treePopup: false,
        ruleForm: {
          recordFile: []
        },
        rules: {
          recordFile: [{
            required: true,
            validator: validateRecordFiles,
            trigger: 'change'
          }]
        }
      };
    },
    components: {
      TreeEdit
    },
    computed: {},
    created() {
      this.getTreeData();
    },
    mounted() {
      openDb();
    },
    methods: {
      getTreeData() {
        this.$api.bridge.AllTheBridges()
          .then((response) => {
            if (response.data.success) {
              this.bridgesList = response.data.data[0];
              const _data = response.data.data[0];

              //构建顶级 第一级
              if (_data.length > 0) {
                //默认选中第一个
                this.checkedId = _data[0].id;
                this.checkedIdName = _data[0].name;
                this.ownId = _data[0].id;
                this.checkedKeys = [_data[0].id];
                this.expandedKeys = [_data[0].id];

                let _treeData = _data.map((item, index) => ({
                  id: item.id,
                  data: [{
                    id: item.id,
                    ownId: item.id,
                    pid: null,
                    label: item.name,
                    level: 1,
                    childFolders: [],
                    index: index
                  }]
                }));
                this.getListData(1);
                this.querySubTreeList(_data).then((response) => {
                  response.map((item, index) => {
                    _treeData[index].data[0].childFolders = this.recursionTreeData(item.data.data, 1, index);
                  });
                  this.$store.dispatch('bridgeRecords/updateTreeData', _treeData);
                  this.updateEditTreeData();
                });
              } else {
                this.$store.dispatch('bridgeRecords/updateTreeData', []);
              }
            }
          });
      },
      querySubTreeList(list) {
        let _list = list.map(item => {
          let _param = {
            ownId: item.id,
            pId: '-1',
            autoBuild: 1
          };
          return this.$api.file.querySubTree(_param);
        });
        return Promise.all(_list).then(function (dataList) {
          return dataList;
        });
      },
      recursionTreeData(data, level, index) {
        let _arr = [];
        let _obj = {};
        data.forEach(item => {
          const _tmp = {
            ...item,
            level,
            index
          };
          if (_tmp.childFolders) {
            _tmp.childFolders = this.recursionTreeData(_tmp.childFolders, _tmp.level, _tmp.index);
          }
          _obj = {
            id: _tmp.id,
            pid: _tmp.pid,
            ownId: _tmp.ownId,
            label: _tmp.name,
            level: _tmp.level + 1,
            childFolders: _tmp['childFolders'] || [],
            index: _tmp.index
          }
          _arr.push(_obj);
        });
        return _arr;
      },
      handleEditTree(node, data, e) {
        e = event || window.event;
        e.stopPropagation();
        this.treePopup = true;
        const _editTreeData = [];
        let _editTreeIndex = null;
        if (data) {
          this.$store.state.bridgeRecords.treeData.forEach((item, index) => {
            if (item.id === data.id) {
              _editTreeData.push(data);
              _editTreeIndex = index;
            }
          })
        }
        this.$store.dispatch('bridgeRecords/updateEditTreeData', _editTreeData);
        this.$store.dispatch('bridgeRecords/updateEditTreeIndex', _editTreeIndex);
      },
      updateEditTreeData() {
        const _editTreeIndex = deepClone(this.$store.state.bridgeRecords.editTreeIndex);
        const _treeData = deepClone(this.$store.state.bridgeRecords.treeData);
        let _editTreeData = _editTreeIndex === null ? [] : _treeData[_editTreeIndex]['data'];
        this.$store.dispatch('bridgeRecords/updateEditTreeData', _editTreeData);
      },
      cancelTreeSubmit() {
        this.treePopup = false;
        this.$refs.treeEdit.closeEdit();
      },
      treeSubmit() {
        this.treePopup = false;
      },
      handleNodeClick(data, checked, child) {
        this.ownId = data.ownId;
        this.checkedId = data.id;
        this.checkedIdName = data.label;
        this.checkedKeys = [data.id];
        this.$refs['tree'][data.index].setCheckedKeys([data.id]);
        this.getListData(1);
      },
      handleCheckChange(data, checked, child) {

        if (checked === true) {
          this.$store.state.bridgeRecords.treeData.forEach((item, index) => {
            if (data.index === index) {
              this.$refs['tree'][index].setCheckedKeys([data.id]);
            }
            this.$refs['tree'][index].setCheckedKeys([]);
          });
          this.checkedKeys = [data.id];
          this.checkedId = data.id;
          this.checkedIdName = data.label;
          this.ownId = data.ownId;
          this.getListData(1);
        } else {
          if (this.checkedId === data.id) {
            this.checkedId = null;
            this.checkedIdName = '';
            this.ownId = null;
            this.checkedKeys = [];
            this.$store.state.bridgeRecords.treeData.forEach((item, index) => {
              this.$refs['tree'][index].setCheckedKeys([]);
            });
            this.getListData(1);
          }
        }
      },
      handleAdd() {
        if (!this.ownId) {
          this.$vs.notify({
            text: "请先选择桥梁！",
            color: "danger"
          });
          return false;
        }
        this.recordPopupTitle = "新增档案";
        this.editRecord = false;
        this.recordPopup = true;
        this.emptyForm();
        this.uploadParams = {
          ownId: this.ownId
        }
        if (this.checkedId) {
          this.uploadParams['folderId'] = this.checkedId;
        }
      },
      emptyForm() {
        this.$refs["ruleForm"].resetFields();
        const emptyObj = {
          recordFile: []
        }
        this.ruleForm = emptyObj;
        this.uploadParams = {};
      },
      handleCheck(index) {
        this.$set(this.listData[index], 'isCheck', !this.listData[index]['isCheck']);
      },
      handleDeleteList() {
        const checkList = this.listData.filter(item => item.isCheck);
        if (checkList.length <= 0) {
          this.$vs.notify({
            text: "请选择要删除的档案",
            color: "danger"
          })
          return false;
        }
        const _ids = checkList.map(item => item.id);
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$api.file.deleteFiles({
            data: _ids
          }).then(response => {
            if (response.data.code === 200) {
              let maxPage = Math.ceil((this.recordsTotal - checkList.length) / this.pageSize);
              if (this.currentPage > maxPage) {
                this.currentPage = maxPage
              }
              this.handlePageChange(this.currentPage);
              this.$vs.notify({
                text: "删除成功",
                color: "success"
              });
            }
          })
        }).catch(() => {
          this.$vs.notify({
            text: '删除失败',
            color: "danger"
          })
        });
      },
      handleEditList() {
        const checkList = this.listData.filter(item => item.isCheck);
        if (checkList.length <= 0) {
          this.$vs.notify({
            text: "请选择要编辑的档案",
            color: "danger"
          });
          return false;
        } else if (checkList.length > 1) {
          this.$vs.notify({
            text: "一次只能编辑一个档案",
            color: "danger"
          });
          return false;
        }
        this.recordPopup = true;
        this.recordPopupTitle = "编辑档案";
        this.editRecord = true;
        this.getFileDetailById(checkList[0].id);
        this.uploadParams = {
          id: checkList[0].id
        };
      },
      handleDownLoadList() {
        const checkList = this.listData.filter(item => item.isCheck);
        if (checkList.length <= 0) {
          this.$vs.notify({
            text: "请选择要下载的档案",
            color: "danger"
          });
          return false;
        }
        this.$confirm('此操作将开始下载, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let _ids = checkList.map(item => item.id);
          if (_ids.length > 1) {
            let _url = `${base.DOWNLOADURL}/api/file/zip/${_ids.join(',')}`;
            this.downLoadFile(_url);
          } else {
            let _url = `${base.DOWNLOADURL}/api/file/file/${_ids.join(',')}`;
            this.downLoadFile(_url);
          }
        }).catch(() => {
          this.$vs.notify({
            text: "已取消下载",
            color: "primary"
          });
        });
      },
      cancelFormSubmit() {
        this.recordPopup = false;
      },
      submit() {
        this.$refs.ruleForm.validate(async (valid, model) => {
          if (!valid) {
            return false;
          }

          this.recordPopup = false;
          this.getListData(1);
        });
      },
      handleSuccess(res, file) {
        if (res.code === 200) {
          if (res.data.successFiles) {
            let _id = res.data.successFiles[0].id;
            let _ext = res.data.successFiles[0].fileSuffix;
            let _filePath = res.data.successFiles[0].filePath;
            let _name = res.data.successFiles[0].originalFileName;

            this.ruleForm.recordFile.push({
              id: _id,
              fileType: _ext,
              filePath: _filePath,
              name: `${_name}.${_ext}`
            });

            if (_ext === 'obj' || _ext === 'mtl') {

              updateBridModel(this.ownId, _ext, _filePath);

            }
          }
        }
      },
      handleRemove(file, fileList) {
        // this.$api.file.deleteFiles({
        //   data: [file.id]
        // }).then(response => {
        //   if (response.data.code === 200) {
        //     this.$set(this.ruleForm, 'recordFile', fileList);
        //   } else {
        //     this.$vs.notify({
        //       text: "删除失败",
        //       color: "danger"
        //     });
        //   }
        // })
        this.$set(this.ruleForm, 'recordFile', fileList);
      },
      handleExceed(files, fileList) {
        this.$vs.notify({
          text: `编辑态，先删除原有文件，重新上传一个文件`,
          color: "danger"
        });
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${file.name}？`);
      },
      handlePageChange(currentPage) {
        this.currentPage = currentPage;
        this.getListData();
      },
      getListData(pageIndex) {
        if (!this.checkedId) {
          this.$vs.notify({
            text: "请选择桥梁或文件夹",
            color: "danger"
          });
          this.listData = [];
          return false;
        }
        if (pageIndex && pageIndex === 1) {
          this.currentPage = 1;
        }
        this.$api.file
          .queryFilesByFolderId(this.currentPage - 1, this.pageSize, {
            folderId: this.checkedId
          }).then((response) => {
          if (response.data.code === 200) {
            this.listData = response.data.data.list || [];
            this.recordsTotal = response.data.data.total || 0;
          }
        });
        this.listData = this.listData.map(item => {
          return Object.assign({}, item, {
            isCheck: false
          });
        });
      },
      getFileDetailById(itemId) {
        const param = {
          id: itemId
        };
        this.$api.file
          .queryFileDetailById(param)
          .then((response) => {
            if (response.data.code === 200) {
              const _data = response.data.data;
              let _recordFile = [{
                id: _data.id,
                fileType: _data.fileSuffix,
                filePath: _data.filePath,
                name: `${_data.originalFileName}.${_data.fileSuffix}`
              }];
              this.ruleForm = {
                recordFile: _recordFile
              }
            }
          })
          .catch(() => {});
      },
      downLoadFile(url) {
        const iframe = document.createElement("iframe");
        iframe.style.display = "none";
        iframe.style.height = 0;
        iframe.src = url;
        document.body.appendChild(iframe);
        setTimeout(() => {
          iframe.remove();
        }, 5 * 60 * 1000);
      },
    }
  };

</script>
<style scoped lang="scss">
  /deep/.el-table__header tr,
  .el-table__header th {
    padding: 0;
    height: 44px;
  }

  /deep/.el-tree {
    margin-bottom: 10px;
  }

  .upload-labelInfo {
    font-size: 12px;
    color: red;
  }

  .record {
    width: 100%;
    display: flex;
    justify-content: space-between;

    .mLeft20 {
      margin-left: 20px;
    }

    .mRight6 {
      margin-right: 6px;
    }

    .mLeft6 {
      margin-left: 6px;
    }

    .bold {
      font-weight: bolder;
      font-size: 16px;
    }

    .custom-tree-node {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;

      i {
        color: #bec4d0;
      }
    }

    .tree-text-length {
      display: inline-block;
      width: 95%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .myTree {
      overflow-y: scroll !important;
    }

    &-upload {
      width: 50px;
      height: 50px;
      background: rgba(248, 250, 255, 1);
      border-radius: 2px;
      border: 1px dashed rgba(64, 158, 255, 1);
      color: #8c939d;
      font-size: 24px;
      padding-top: 12px;
    }

    &-left {
      width: 18%;
      height: 86vh;

      &-header {
        overflow: hidden;
        margin-bottom: 18px;

        span {
          display: block;
          float: left;
          font-size: 16px;
          font-weight: 500;
          color: rgba(50, 123, 220, 1);
          line-height: 30px;
        }

        div {
          cursor: pointer;
          float: right;
          background: rgba(50, 123, 220, 1);
          width: 48px;
          height: 30px;
          color: #fff;
          font-size: 14px;
          text-align: center;
          line-height: 30px;
          border-radius: 4px;
        }
      }
    }

    &-right {
      width: 80%;
    }

    &-searchBar {
      padding: 15px;
      background: rgba(255, 255, 255, 1);
      box-shadow: 0px 0px 5px 0px rgba(232, 232, 232, 0.53);
      border-radius: 2px;
    }

    &-flexBetween {
      display: flex;
      justify-content: space-between;
    }

    &-content {
      margin-top: 10px;
      width: 100%;

      &-header {
        width: 100%;
        height: 48px;
        background: rgba(233, 237, 245, 1);
        padding: 13px 13px 13px 20px;
        overflow: hidden;

        h4 {
          font-size: 16px;
          font-weight: 500;
          color: rgba(78, 93, 113, 1);
          line-height: 22px;
          float: left;
        }

        &-btns {
          float: right;
          margin-top: -8px;
        }
      }

      &-main {
        width: 100%;
        height: calc(86vh - 63px - 10px - 48px);
        background: rgba(255, 255, 255, 1);
        box-shadow: 0px 0px 5px 0px rgba(232, 232, 232, 0.53);
        border-radius: 2px;
        padding: 26px 20px;
      }

      &-list {
        overflow: hidden;
        width: 100%;
        height: calc(100% - 60px);
        overflow-y: auto;
        position: relative;
      }

      &-item {
        width: calc((100% - 140px) / 8);
        height: calc((100% - 60px) / 3);
        min-height: 136px;
        background: rgba(233, 237, 244, 1);
        border-radius: 2px;
        float: left;
        margin-bottom: 20px;
        padding-top: 30px;
        position: relative;
        cursor: pointer;

        &:not(:nth-child(8n)) {
          margin-right: 20px;
        }

        &-check {
          position: absolute;
          right: 5px;
          top: 5px;
          cursor: pointer;

          .notCheck {
            display: block;
            width: 16px;
            height: 16px;
            background: rgba(255, 255, 255, 1);
            border: 2px solid rgba(50, 123, 220, 1);
            border-radius: 50%;
          }

          .hasCheck {
            display: block;
            width: 16px;
            height: 16px;
            background: rgba(50, 123, 220, 1);
            border: 2px solid rgba(50, 123, 220, 1);
            border-radius: 50%;
            color: #fff;
            font-weight: bold;
            font-size: 12px;
            line-height: 14px;
            text-align: center;
          }
        }

        &-bg {
          width: 63px;
          height: 70px;
          background: url('../../assets/images/pages/record_bg.png') no-repeat;
          background-size: 100% 100%;
          margin: auto;
          position: relative;

          .label {
            position: absolute;
            bottom: 10px;
            left: 6px;
            font-size: 13px;
            font-weight: 600;
            color: rgba(255, 255, 255, 1);
          }
        }

        &-title {
          width: 75px;
          margin: auto;
          font-size: 12px;
          font-weight: 500;
          color: rgba(50, 123, 220, 1);
          margin-top: 10px;
          text-align: center;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;

        }
      }

      &-page {
        margin-top: 20px;
        text-align: center;
      }

      &-noData {
        width: 500px;
        height: 294px;
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        margin: auto;
        background: url("../../../src/assets/images/pages/bg_noData.png");
        background-size: 100% 100%;

      }
    }
  }

</style>
